import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:my_meeting/utils/log_utils.dart';
import 'package:syncfusion_flutter_sliders/sliders.dart';
import 'package:timezone/timezone.dart' as tz;

import '../../generated/l10n.dart';
import '../../widget/dialog/dialog_facilities.dart';

class AppointmentLogic extends GetxController {
  var isBtnEnabled = false.obs;
  final List<Map<String, String>> dates = [];
  var dateIndex = 100.obs;
  var sfSliderIndex1 = 6.obs;
  var sfSliderIndex2 = 6.obs;

  var sfRangeValues = const SfRangeValues(9.0, 12.0).obs;

  var startTime = 9.obs;
  var endTime = 12.obs;

  /// 设施
  int facilitieIndex = -1;

  DateFormat dateFormat = DateFormat('MM/dd');
  DateFormat dateFormat2 = DateFormat('yyyy.MM.dd');

  @override
  void onInit() {
    super.onInit();
    getFutureDates();
  }

  List<Map<String, String>> getFutureDates() {
    final now = DateTime.now(); // 获取当前时间
    final localTimeZone = tz.local; // 获取本地时区

    for (int i = 0; i < 7; i++) {
      final futureDate = now.add(Duration(days: i));
      final localDate = tz.TZDateTime.from(futureDate, localTimeZone);
      String dateFormatted = dateFormat.format(localDate);
      String dateFormatted2 = dateFormat2.format(localDate);
      String weekdayFormatted = DateFormat.E().format(localDate); // 获取星期几

      if (i == 0) {
        dateFormatted = S.current.today;
      }
      if (Intl.getCurrentLocale().contains('zh')) {
        weekdayFormatted = weekdayFormatted.substring(1);
      }
      dates.add({
        'date': dateFormatted, // date
        'weekday': weekdayFormatted, // 星期几
        'date2': dateFormatted2, // 2024.08.23 格式
      });
    }

    return dates;
  }

  ///设施
  void facilitie() {
    Get.dialog(DialogFacilities(facilitieCallback: (index) {
      facilitieIndex = index;
      checkBtnEnabled();
    }));
  }

  void checkBtnEnabled() {
    LogD(
        '========facilitieIndex: $facilitieIndex dateIndex: ${dateIndex.value}');
    if (dateIndex.value != 100 && facilitieIndex != -1) {
      isBtnEnabled.value = true;
    } else {
      isBtnEnabled.value = false;
    }
  }

  void nextStep() {
    Map map = {
      'date': dates[dateIndex.value]['date2'],
      'startTime': doubleToTime(sfRangeValues.value.start),
      'endTime': doubleToTime(sfRangeValues.value.end),
      'facilitieIndex': facilitieIndex,
    };
    LogD('========nextStep:   map: ${map}');
    Get.back(result: map);
  }

  String doubleToTime(double value) {
    // 将值分解为小时和分钟
    int hours = value.toInt();
    int minutes = ((value - hours) * 60).toInt();

    // 格式化小时和分钟为两位数
    String formattedTime =
        '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}';
    return formattedTime;
  }
}
